package com.iplant.basic.serviceImpl.dao.bms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.aspectj.apache.bcel.generic.RET;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.po.enums.UserGrads;
import com.iplant.base.utils.SessionConstants;
import com.iplant.base.utils.general.DesUtil;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.utils.Constants;

public class BMSEmployeeDAO extends BaseDAO {

    private static Logger logger = LoggerFactory.getLogger(BMSEmployeeDAO.class);

    private static BMSEmployeeDAO Instance = null;

    private BMSEmployeeDAO() {
        super();
    }

    public static BMSEmployeeDAO getInstance() {
        if (Instance == null)
            Instance = new BMSEmployeeDAO();
        return Instance;
    }
    // 用户管理接口函数
    // 用户管理逻辑函数

    private boolean MBS_CheckLoginName(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        boolean wResult = false;
        try {
            // wSqlDataReader\[(\"\w+\")\] wSqlDataReader.get($1)
            wErrorCode.set(0);

            String wSQLText = "";
            wSQLText = StringUtils.Format("Select Count(*) As UserCount from {0}.mbs_user", super.getDBName())
                    + " where ID!=:ID and LoginName=:LoginName";

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();

            wParams.put("ID", wEmployee.ID);
            wParams.put("LoginName", wEmployee.LoginName);
            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                int wUserCount = StringUtils.parseInt(wSqlDataReader.get("UserCount"));
                if (wUserCount > 0)
                    wResult = true;
            }

        } catch (Exception ex) {
            logger.error("MBS_CheckLoginName ", ex);
        }
        return wResult;
    }

    public BMSEmployee BMS_LoginEmployeeByToken(String wLoginName, String wToken, OutResult<Integer> wErrorCode) {
        BMSEmployee wEmployee = new BMSEmployee();
        wEmployee.ID = -1;
        try {
            int wCompanyID = this.BMS_LoginByStoken(wLoginName, wToken, wErrorCode);
            if (wCompanyID >= 0) {

                if (DesUtil.encrypt(wLoginName).equalsIgnoreCase(BMSEmployee.SysAdmin.LoginName)) {
                    return BMSEmployee.SysAdmin;
                }
                if (StringUtils.parseInt(wLoginName) > Constants.EngineerUserIDMin) {
                    Optional<BMSEmployee> wBMSEmployeeOptional = Constants.GetEngineerUserList().stream()
                            .filter(p -> p.LoginName.equalsIgnoreCase(wLoginName)).findAny();
                    if (wBMSEmployeeOptional.isPresent()) {
                        wEmployee = wBMSEmployeeOptional.get();
                        wEmployee.LoginName = DesUtil.encrypt(wEmployee.LoginName);
                        return wEmployee;
                    }
                }
                if (super.getDBName().length() < 1) {
                    wEmployee.ID = -5;
                    return wEmployee;
                }

                String wSQLText = StringUtils.Format("select  u.*,t1.Name as Department,t2.Name as PositionName,"
                        + " t3.Name as CreatorName ,t4.Name as EditorName from {0}.mbs_user u "
                        + " left join {0}.bms_department t1 on u.DepartmentID=t1.ID "
                        + " left join {0}.bms_position t2 on u.Position=t2.ID "
                        + " left join {0}.mbs_user t3 on u.CreatorID=t3.ID "
                        + " left join {0}.mbs_user t4 on u.EditorID=t4.ID "
                        + " where u.LoginName=:LoginName and u.Active=1", super.getDBName());

                Map<String, Object> wParams = new HashMap<String, Object>();
                wParams.clear();

                wParams.put("LoginName", wLoginName);
                wSQLText = this.DMLChange(wSQLText);
                List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
                for (Map<String, Object> wSqlDataReader : wQueryResultList) {

                    wEmployee.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                    wEmployee.CompanyID = wCompanyID;
                    wEmployee.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                    wEmployee.Password = StringUtils.parseString(wSqlDataReader.get("Password"));
                    wEmployee.LoginName = DesUtil.encrypt(StringUtils.parseString(wSqlDataReader.get("LoginName")));
                    wEmployee.Password = StringUtils.parseString(wSqlDataReader.get("Password"));
                    wEmployee.DepartmentID = StringUtils.parseInt(wSqlDataReader.get("DepartmentID"));
                    wEmployee.Department = StringUtils.parseString(wSqlDataReader.get("Department"));

                    wEmployee.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                    wEmployee.Grad = StringUtils.parseInt(wSqlDataReader.get("Grad"));
                    wEmployee.Manager = StringUtils.parseInt(wSqlDataReader.get("Manager"));
                    wEmployee.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                    wEmployee.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                    wEmployee.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                    wEmployee.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                    wEmployee.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                    wEmployee.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                    wEmployee.LoginID = StringUtils.parseString(wSqlDataReader.get("LoginID"));
                    wEmployee.FaceIcon = StringUtils.parseString(wSqlDataReader.get("FaceIcon"));

                    wEmployee.Phone = StringUtils.parseString(wSqlDataReader.get("Phone"));
                    wEmployee.PhoneMAC = StringUtils.parseLong(wSqlDataReader.get("PhoneMAC"));

                    wEmployee.Email = StringUtils.parseString(wSqlDataReader.get("Email"));
                    wEmployee.WeiXin = StringUtils.parseString(wSqlDataReader.get("WeiXin"));

                    wEmployee.Position = StringUtils.parseInt(wSqlDataReader.get("Position"));
                    wEmployee.PositionName = StringUtils.parseString(wSqlDataReader.get("PositionName"));
                    wEmployee.Description = StringUtils.parseString(wSqlDataReader.get("Description"));
                    wEmployee.DutyID = StringUtils.parseInt(wSqlDataReader.get("DutyID"));
                    boolean wDBOnline = StringUtils.parseBoolean(wSqlDataReader.get("Online"));

                    wEmployee.Online = wDBOnline ? 1 : 0;
                    wEmployee.OnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("OnLineTime"));
                    if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                        wEmployee.Grad = UserGrads.Default.getValue();
                    }

                }
            }
        } catch (Exception ex) {
            logger.error("BMS_LoginEmployeeByToken ", ex);
            wEmployee.ID = -3;
        }
        return wEmployee;
    }

    public BMSEmployee BMS_LoginEmployee(String wLoginName, String wPassword, long wMAC,
                                         OutResult<Integer> wErrorCode) {
        BMSEmployee wEmployee = new BMSEmployee();
        wEmployee.ID = -1;
        try {
            String wDESPassword = DesUtil.encrypt(wPassword, SessionConstants.appSecret);

            if (DesUtil.encrypt(wLoginName, SessionConstants.appSecret).equalsIgnoreCase(BMSEmployee.SysAdmin.LoginName)
                    && wDESPassword.equalsIgnoreCase(BMSEmployee.SysAdmin.Password)) {
                return BMSEmployee.SysAdmin;
            }
            if (StringUtils.parseInt(wLoginName) > Constants.EngineerUserIDMin) {
                // 开发登录
                Optional<BMSEmployee> wOptional = Constants.GetEngineerUserList().stream().filter(
                                p -> p.LoginName.equalsIgnoreCase(wLoginName) && p.Password.equalsIgnoreCase(wDESPassword))
                        .findFirst();

                if (wOptional.isPresent()) {
                    wEmployee = wOptional.get();
                    wEmployee.LoginName = DesUtil.encrypt(wEmployee.LoginName, SessionConstants.appSecret);
                    return wEmployee;
                }

            }

            if (super.getDBName().length() < 1) {
                wEmployee.ID = -5;
                return wEmployee;
            }

            String wSQLText = StringUtils.Format("select u.*,t1.Name as Department,t2.Name as PositionName ,"
                    + " t3.Name as CreatorName ,t4.Name as EditorName from {0}.mbs_user u "
                    + " left join {0}.bms_department t1 on u.DepartmentID=t1.ID "
                    + " left join {0}.bms_position t2 on u.Position=t2.ID "
                    + " left join {0}.mbs_user t3 on u.CreatorID=t3.ID "
                    + " left join {0}.mbs_user t4 on u.EditorID=t4.ID "
                    + " where u.LoginName=:LoginName and u.Active=1", super.getDBName());

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();

            wParams.put("LoginName", wLoginName);
            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wEmployee.ID = -2;
                String wDBPassword = StringUtils.parseString(wSqlDataReader.get("Password"));

                if (wDESPassword.equalsIgnoreCase(wDBPassword)) {
                    wEmployee.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                    wEmployee.CompanyID = StringUtils.parseInt(wSqlDataReader.get("CompanyID"));
                    wEmployee.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                    wEmployee.LoginName = DesUtil.encrypt(StringUtils.parseString(wSqlDataReader.get("LoginName")),
                            SessionConstants.appSecret);
                    wEmployee.Password = StringUtils.parseString(wSqlDataReader.get("Password"));
                    wEmployee.DepartmentID = StringUtils.parseInt(wSqlDataReader.get("DepartmentID"));
                    wEmployee.Department = StringUtils.parseString(wSqlDataReader.get("Department"));

                    wEmployee.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                    wEmployee.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                    wEmployee.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                    wEmployee.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                    wEmployee.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                    wEmployee.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                    wEmployee.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                    wEmployee.Grad = StringUtils.parseInt(wSqlDataReader.get("Grad"));
                    wEmployee.Manager = StringUtils.parseInt(wSqlDataReader.get("Manager"));
                    wEmployee.LoginID = StringUtils.parseString(wSqlDataReader.get("LoginID"));
                    wEmployee.FaceIcon = StringUtils.parseString(wSqlDataReader.get("FaceIcon"));
                    wEmployee.Phone = StringUtils.parseString(wSqlDataReader.get("Phone"));
                    wEmployee.PhoneMAC = StringUtils.parseLong(wSqlDataReader.get("PhoneMAC"));

                    wEmployee.Email = StringUtils.parseString(wSqlDataReader.get("Email"));
                    wEmployee.WeiXin = StringUtils.parseString(wSqlDataReader.get("WeiXin"));

                    wEmployee.Position = StringUtils.parseInt(wSqlDataReader.get("Position"));
                    wEmployee.PositionName = StringUtils.parseString(wSqlDataReader.get("PositionName"));
                    wEmployee.DutyID = StringUtils.parseInt(wSqlDataReader.get("DutyID"));
                    boolean wDBOnline = StringUtils.parseBoolean(wSqlDataReader.get("Online"));
                    wEmployee.Password = wDBPassword;
                    wEmployee.Online = wDBOnline ? 1 : 0;
                    wEmployee.OnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("OnLineTime"));
                    wEmployee.LastOnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("LastOnLineTime"));
                    if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                        wEmployee.Grad = UserGrads.Default.getValue();
                    }
                }
            }

        } catch (Exception ex) {
            logger.error("BMS_LoginEmployee ", ex);
            wEmployee.ID = -3;
        }
        return wEmployee;
    }

    public BMSEmployee BMS_LoginEmployeeByUserName(String wUserName, String wPassword, OutResult<Integer> wErrorCode) {
        BMSEmployee wEmployee = new BMSEmployee();
        wErrorCode.set(0);
        try {
            String wDESPassword = DesUtil.encrypt(wPassword, SessionConstants.appSecret);

            if (DesUtil.encrypt(wUserName, SessionConstants.appSecret).equalsIgnoreCase(BMSEmployee.SysAdmin.LoginName)
                    && wDESPassword.equalsIgnoreCase(BMSEmployee.SysAdmin.Password)) {
                return BMSEmployee.SysAdmin;
            }


            String wSQLText = StringUtils.Format(
                    "select u.*,t5.Name as CreatorName,t6.Name as EditorName, t1.Name as Department,"
                            + " t1.Code as DepartmentCode,t2.Name as PositionName from {0}.mbs_user u"
                            + " left join {0}.mbs_user t5 on t5.ID=u.CreatorID "
                            + " left join {0}.mbs_user t6 on t6.ID=u.EditorID "
                            + " left join {0}.bms_department t1 on u.DepartmentID=t1.ID "
                            + " left join {0}.bms_position t2 on u.Position=t2.ID "
                            + " where u.Name=:Name and u.Password =:Password and  u.Active=1",
                    super.getDBName());

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("Name", wUserName);
            wParams.put("Password", wDESPassword);
            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wEmployee.ID = -2;
                String wDBPassword = StringUtils.parseString(wSqlDataReader.get("Password"));

                if (wDESPassword.equalsIgnoreCase(wDBPassword)) {
                    wEmployee.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                    wEmployee.CompanyID = StringUtils.parseInt(wSqlDataReader.get("CompanyID"));
                    wEmployee.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                    wEmployee.LoginName = DesUtil.encrypt(StringUtils.parseString(wSqlDataReader.get("LoginName")),
                            SessionConstants.appSecret);
                    wEmployee.Password = StringUtils.parseString(wSqlDataReader.get("Password"));
                    wEmployee.DepartmentID = StringUtils.parseInt(wSqlDataReader.get("DepartmentID"));
                    wEmployee.Department = StringUtils.parseString(wSqlDataReader.get("Department"));

                    wEmployee.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                    wEmployee.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                    wEmployee.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                    wEmployee.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                    wEmployee.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                    wEmployee.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                    wEmployee.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                    wEmployee.Grad = StringUtils.parseInt(wSqlDataReader.get("Grad"));
                    wEmployee.Manager = StringUtils.parseInt(wSqlDataReader.get("Manager"));
                    wEmployee.LoginID = StringUtils.parseString(wSqlDataReader.get("LoginID"));
                    wEmployee.FaceIcon = StringUtils.parseString(wSqlDataReader.get("FaceIcon"));
                    wEmployee.Phone = StringUtils.parseString(wSqlDataReader.get("Phone"));
                    wEmployee.PhoneMAC = StringUtils.parseLong(wSqlDataReader.get("PhoneMAC"));

                    wEmployee.Email = StringUtils.parseString(wSqlDataReader.get("Email"));
                    wEmployee.WeiXin = StringUtils.parseString(wSqlDataReader.get("WeiXin"));

                    wEmployee.Position = StringUtils.parseInt(wSqlDataReader.get("Position"));
                    wEmployee.PositionName = StringUtils.parseString(wSqlDataReader.get("PositionName"));
                    wEmployee.DutyID = StringUtils.parseInt(wSqlDataReader.get("DutyID"));
                    boolean wDBOnline = StringUtils.parseBoolean(wSqlDataReader.get("Online"));
                    wEmployee.Password = wDBPassword;
                    wEmployee.Online = wDBOnline ? 1 : 0;
                    wEmployee.OnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("OnLineTime"));
                    wEmployee.LastOnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("LastOnLineTime"));
                    if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                        wEmployee.Grad = UserGrads.Default.getValue();
                    }
                }
            }
            if (wEmployee.ID == 0) {
                wErrorCode.set(ExceptionTypes.UserValidationFailed.getValue());
            }
        } catch (Exception ex) {
            logger.error("BMS_LoginEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wEmployee;
    }

    public void BMS_AddEmployee(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {

        try {
            wErrorCode.set(0);
            String wDefaultPassword = DesUtil.encrypt(BMSEmployee.defaultPassword, SessionConstants.appSecret);

            Map<String, Object> wParams = new HashMap<String, Object>();

            BMSEmployee wBMSEmployeeDB = null;
            if (StringUtils.isNotEmpty(wEmployee.LoginID) && wEmployee.LoginID.length() > 6) {
                // 检查LoginID唯一性 检查LoginID在LoginName中的唯一性
                wBMSEmployeeDB = this.BMS_QueryEmployeeByLoginID(wLoginUser, wEmployee.LoginID, wErrorCode);
                if (wBMSEmployeeDB.ID > 0) {
                    wErrorCode.set(ExceptionTypes.Logic.getValue());
                    return;
                }

                if (StringUtils.isEmpty(wEmployee.LoginName)) {
                    wEmployee.LoginName = wEmployee.LoginID;
                }

            }
            if (StringUtils.isNotEmpty(wEmployee.LoginName) && wEmployee.LoginName.length() >= 6) {
                // 检查LoginID唯一性 检查LoginID在LoginName中的唯一性
                wBMSEmployeeDB = this.BMS_QueryEmployeeByLoginName(wLoginUser, wEmployee.LoginName, wErrorCode);
                if (wBMSEmployeeDB.ID > 0) {
                    wErrorCode.set(ExceptionTypes.Logic.getValue());
                    return;
                }
            }

            wParams.put("Name", wEmployee.Name);
            wParams.put("LoginName", wEmployee.LoginName);
            wParams.put("Password", wDefaultPassword);
            wParams.put("Email", wEmployee.Email);
            wParams.put("Phone", wEmployee.Phone);
            wParams.put("PhoneMAC", wEmployee.PhoneMAC);

            wParams.put("DepartmentID", wEmployee.DepartmentID);
            wParams.put("CreateTime", Calendar.getInstance());
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("CreatorID", wLoginUser.ID);
            wParams.put("EditorID", wLoginUser.ID);
            wParams.put("WeiXin", wEmployee.WeiXin);

            if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                wEmployee.Grad = UserGrads.Default.getValue();
            }

            wParams.put("Grad", wEmployee.Grad);
            wParams.put("Manager", wEmployee.Manager);
            wParams.put("Position", wEmployee.Position);
            wParams.put("DutyID", wEmployee.DutyID);
            wParams.put("LoginID", wEmployee.LoginID);
            wParams.put("FaceIcon", wEmployee.FaceIcon);
            wParams.put("Active", wEmployee.Active);
            wParams.put("Online", 1);
            wParams.put("OnLineTime", Calendar.getInstance());
            wParams.put("DepartureDate", Calendar.getInstance());
            wParams.put("LastOnLineTime", Calendar.getInstance());
            wParams.put("Type", wEmployee.Type);
            wParams.put("SuperiorID", wEmployee.SuperiorID);
            wParams.put("Description", wEmployee.Description);


            wEmployee.ID = super.Insert(StringUtils.Format("{0}.mbs_user", super.getDBName()), wParams);

            if (StringUtils.isEmpty(wEmployee.LoginName) && wEmployee.ID > 0) {
                wEmployee.LoginName = String.format("%06d", wEmployee.ID);

                wParams.clear();

                wParams.put("LoginName", wEmployee.LoginName);
                wParams.put("ID", wEmployee.ID);

                super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams);

            }
        } catch (Exception ex) {
            logger.error("BMS_addEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
    }

    public void BMS_UpdateOnline(BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {

        try {
            if (wEmployee == null || wEmployee.ID <= 0 || wEmployee.ID >= Constants.EngineerUserIDMin) {
                return;
            }

            wEmployee.Online = 1;
            Calendar wBaseTime = Calendar.getInstance();
            wBaseTime.set(2020, 0, 1);

            if (wEmployee.LastOnLineTime == null || wEmployee.LastOnLineTime.compareTo(wBaseTime) <= 0)
                wEmployee.LastOnLineTime = Calendar.getInstance();

            if (wEmployee.OnLineTime == null || wEmployee.OnLineTime.compareTo(wBaseTime) <= 0)
                wEmployee.OnLineTime = wEmployee.LastOnLineTime;

            wBaseTime = Calendar.getInstance();
            wBaseTime.add(Calendar.MINUTE, -10);

            if (wEmployee.LastOnLineTime.compareTo(wBaseTime) < 0)
                wEmployee.OnLineTime = Calendar.getInstance();

            wEmployee.LastOnLineTime = Calendar.getInstance();

            wErrorCode.set(0);

            String wSQLText = "";
            wSQLText = StringUtils.Format("Update {0}.mbs_user", super.getDBName())
                    + " Set LastOnLineTime=:LastOnLineTime,OnLineTime=:OnLineTime where ID=:ID";

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("LastOnLineTime", wEmployee.LastOnLineTime);
            wParams.put("OnLineTime", wEmployee.OnLineTime);
            wParams.put("ID", wEmployee.ID);
            wSQLText = this.DMLChange(wSQLText);
            super.update(wSQLText, wParams);
        } catch (Exception ex) {

            logger.error("BMS_UpdateOnline ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
    }

    public int BMS_SaveEmployee(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            if (this.MBS_CheckLoginName(wLoginUser, wEmployee, wErrorCode)){
                wErrorCode.set(ExceptionTypes.Logic.getValue());
                return 0;
            }


            if (wEmployee.Grad > 0)
                wEmployee.Active = 1;

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("Name", wEmployee.Name);
            wParams.put("LoginName", wEmployee.LoginName);
            wParams.put("LoginID", wEmployee.LoginID);
            wParams.put("Type", wEmployee.Type);
            wParams.put("SuperiorID", wEmployee.SuperiorID);
            if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                wEmployee.Grad = UserGrads.Default.getValue();
            }
            wParams.put("Grad", wEmployee.Grad);
            wParams.put("DepartmentID", wEmployee.DepartmentID);
            wParams.put("EditorID", wEmployee.EditorID);
            wParams.put("FaceIcon", wEmployee.FaceIcon);
            wParams.put("Active", wEmployee.Active);
            wParams.put("Manager", wEmployee.Manager);
            wParams.put("Position", wEmployee.Position);
            wParams.put("DutyID", wEmployee.DutyID);
            wParams.put("Phone", wEmployee.Phone);
            wParams.put("PhoneMAC", wEmployee.PhoneMAC);
            wParams.put("Email", wEmployee.Email);
            wParams.put("WeiXin", wEmployee.WeiXin);
            wParams.put("EditTime", Calendar.getInstance());
            wParams.put("Description", wEmployee.Description);

            wParams.put("ID", wEmployee.ID);
            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams);

        } catch (Exception ex) {

            logger.error("BMS_SaveEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    public int BMS_SaveEmployeeSuperiorID(BMSEmployee wLoginUser, BMSEmployee wEmployee,
                                          OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            if (this.MBS_CheckLoginName(wLoginUser, wEmployee, wErrorCode))
                wErrorCode.set(ExceptionTypes.Logic.getValue());

            Map<String, Object> wParams = new HashMap<String, Object>();

            wParams.put("SuperiorID", wEmployee.SuperiorID);

            wParams.put("ID", wEmployee.ID);
            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams);
        } catch (Exception ex) {

            logger.error("BMS_SaveEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    public int BMS_SavePassword(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("Password", DesUtil.encrypt(wEmployee.Password, SessionConstants.appSecret));

            wParams.put("ID", wEmployee.ID);
            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams);

        } catch (Exception ex) {
            logger.error("BMS_SavePassword ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    public int BMS_DisableEmployee(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("ID", wEmployee.ID);
            wParams.put("DepartureDate", Calendar.getInstance());
            wParams.put("Active", 2);

            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams,
                    "  and Grad=0 ");

        } catch (Exception ex) {

            logger.error("BMS_DisableEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    public int BMS_ActiveEmployee(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("ID", wEmployee.ID);
            wParams.put("DepartureDate", Calendar.getInstance());
            wParams.put("Active", 1);

            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams,
                    "  and Grad=0 ");
        } catch (Exception ex) {

            logger.error("BMS_ActiveEmployee ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    public int BMS_ResetPassword(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("ID", wEmployee.ID);

            wParams.put("Password", DesUtil.encrypt(BMSEmployee.defaultPassword, SessionConstants.appSecret));

            super.Update(StringUtils.Format("{0}.mbs_user", super.getDBName()), "ID", wParams,
                    "  and Grad=0 ");
        } catch (Exception ex) {
            logger.error("BMS_ResetPassword ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    private List<BMSEmployee> BMS_QueryEmployeeList(BMSEmployee wLoginUser, List<Integer> wID, String wLoginID,
                                                    String wLoginName, int wDepartmentID, int wPosition,
                                                    int wDepartmentType, int wPositionType, int wActive, String wName,
                                                    Pagination wPagination, OutResult<Integer> wErrorCode) {
        List<BMSEmployee> wEmployeeList = new ArrayList<BMSEmployee>();
        wErrorCode.set(0);
        try {

            if (wLoginID == null)
                wLoginID = "";
            if (wLoginName == null)
                wLoginName = "";

            if (wID == null)
                wID = new ArrayList<Integer>();

            wID.removeIf(p -> p <= 0);
            String wSQLText = StringUtils.Format(

                    "select u.*,t1.Name as Department,t2.Name as PositionName,GROUP_CONCAT(distinct t6.ID) as " +
                            "RoleIDList,"
                            + " GROUP_CONCAT(distinct t6.Name) as RoleName, t5.Name as CreatorName ,t4.Name as " +
                            "EditorName from {0}.mbs_user u "
                            + " left join {0}.bms_department t1 on u.DepartmentID=t1.ID "
                            + " left join {0}.bms_position t2 on u.Position=t2.ID "
                            + " left join {0}.mbs_roleuser t3 on u.ID=t3.UserID "
                            + " left join {0}.mbs_user t5 on u.CreatorID=t5.ID "
                            + " left join {0}.mbs_user t4 on u.EditorID=t4.ID "
                            + " left join {0}.mbs_role t6 on t6.Active=1 and t3.RoleID=t6.ID "
                            + " where (:Active<0  or u.Active=:Active ) "
                            + " and  ( :LoginName = ''''   or u.LoginName=:LoginName )"
                            + " and  ( :LoginID  = ''''   or u.LoginID=:LoginID )"
                            + " and  ( :DepartmentID <=0   or u.DepartmentID=:DepartmentID )"
                            + " and  ( :DepartmentType <=0   or t1.Type=:DepartmentType )"
                            + " and  ( :PositionType <=0   or t2.DutyID=:PositionType )"
                            + " and  ( :Position <=0   or u.Position=:Position )"
                            + " and  ( :wName = ''''   or u.Name like ''%{2}%'' or u.LoginName like ''%{2}%'' or u" +
                            ".LoginID like ''%{2}%'' )"
                            + " and  ( :ID = ''''   or u.ID in ({1}) ) group by u.ID   ",
                    super.getDBName(), wID.size() > 0 ? StringUtils.Join(",", wID) : "0", wName);

            wSQLText = this.DMLChange(wSQLText);
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("Position", wPosition);
            wParams.put("Active", wActive);
            wParams.put("DepartmentID", wDepartmentID);
            wParams.put("DepartmentType", wDepartmentType);
            wParams.put("PositionType", wPositionType);
            wParams.put("ID", StringUtils.Join(",", wID));
            wParams.put("LoginID", wLoginID);
            wParams.put("LoginName", wLoginName);
            wParams.put("wName", wName);

            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParams, wPagination);

            Calendar wBaseTime = Calendar.getInstance();
            wBaseTime.add(Calendar.MINUTE, -10);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {

                BMSEmployee wEmployee = new BMSEmployee();
                wEmployee.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wEmployee.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wEmployee.LoginName = StringUtils.parseString(wSqlDataReader.get("LoginName"));
                wEmployee.LoginID = StringUtils.parseString(wSqlDataReader.get("LoginID"));
                wEmployee.FaceIcon = StringUtils.parseString(wSqlDataReader.get("FaceIcon"));
                wEmployee.Password = StringUtils.parseString(wSqlDataReader.get("Password"));
                wEmployee.DepartmentID = StringUtils.parseInt(wSqlDataReader.get("DepartmentID"));
                wEmployee.Department = StringUtils.parseString(wSqlDataReader.get("Department"));
                wEmployee.SuperiorID = StringUtils.parseInt(wSqlDataReader.get("SuperiorID"));
                wEmployee.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));
                wEmployee.Type = StringUtils.parseInt(wSqlDataReader.get("Type"));

                wEmployee.Grad = StringUtils.parseInt(wSqlDataReader.get("Grad"));
                wEmployee.Manager = StringUtils.parseInt(wSqlDataReader.get("Manager"));
                wEmployee.Position = StringUtils.parseInt(wSqlDataReader.get("Position"));
                wEmployee.PositionName = StringUtils.parseString(wSqlDataReader.get("PositionName"));
                wEmployee.DutyID = StringUtils.parseInt(wSqlDataReader.get("DutyID"));

                wEmployee.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wEmployee.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wEmployee.CreatorName = StringUtils.parseString(wSqlDataReader.get("CreatorName"));
                wEmployee.EditorName = StringUtils.parseString(wSqlDataReader.get("EditorName"));
                wEmployee.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wEmployee.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));

                wEmployee.Phone = StringUtils.parseString(wSqlDataReader.get("Phone"));
                wEmployee.PhoneMAC = StringUtils.parseLong(wSqlDataReader.get("PhoneMAC"));
                wEmployee.Email = StringUtils.parseString(wSqlDataReader.get("Email"));

                wEmployee.WeiXin = StringUtils.parseString(wSqlDataReader.get("WeiXin"));
                wEmployee.Online = StringUtils.parseInt(wSqlDataReader.get("Online"));
                wEmployee.OnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("OnLineTime"));
                wEmployee.LastOnLineTime = StringUtils.parseCalendar(wSqlDataReader.get("LastOnLineTime"));

                wEmployee.RoleIDList = StringUtils
                        .parseIntList(StringUtils.parseString(wSqlDataReader.get("RoleIDList")), ",");

                if (wEmployee.LastOnLineTime.compareTo(wBaseTime) > 0)
                    wEmployee.Online = 1;
                else
                    wEmployee.Online = 0;

                wEmployee.DepartureDate = StringUtils.parseCalendar(wSqlDataReader.get("DepartureDate"));
                if (wEmployee.Active > 0)
                    wEmployee.DepartureDate.add(Calendar.YEAR, 10);

                if (wEmployee.Grad >= UserGrads.Engineer.getValue()) {
                    wEmployee.Grad = UserGrads.Default.getValue();
                }

                wEmployeeList.add(wEmployee);

            }

        } catch (Exception ex) {
            logger.error("BMS_QueryEmployeeList ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wEmployeeList;
    }

    public List<BMSEmployee> BMS_QueryEmployeeList(BMSEmployee wLoginUser, int wDepartmentID, int wPosition,
                                                   int wDepartmentType, int wPositionType, int wActive, String wName,
                                                   Pagination wPagination,
                                                   OutResult<Integer> wErrorCode) {
        List<BMSEmployee> wEmployeeList = new ArrayList<BMSEmployee>();
        try {

            wEmployeeList = this.BMS_QueryEmployeeList(wLoginUser, null, "", "", wDepartmentID, wPosition,
                    wDepartmentType, wPositionType, wActive, wName, wPagination, wErrorCode);
        } catch (Exception ex) {
            logger.error("BMS_QueryEmployeeList ", ex);
            wErrorCode.set(ExceptionTypes.Exception.getValue());
        }
        return wEmployeeList;
    }

    public List<BMSEmployee> BMS_QueryEmployeeList(BMSEmployee wLoginUser, List<Integer> wID,
                                                   OutResult<Integer> wErrorCode) {
        List<BMSEmployee> wEmployeeList = new ArrayList<BMSEmployee>();
        try {

            wEmployeeList = this.BMS_QueryEmployeeList(wLoginUser, wID, "", "", -1, -1, -1, -1, -1, "",
                    Pagination.getDefault(), wErrorCode);
        } catch (Exception ex) {
            logger.error("BMS_QueryEmployeeList ", ex);
            wErrorCode.set(ExceptionTypes.Exception.getValue());
        }
        return wEmployeeList;
    }

    public BMSEmployee BMS_QueryEmployeeByLoginID(BMSEmployee wLoginUser, String wLoginID,
                                                  OutResult<Integer> wErrorCode) {
        BMSEmployee wBMSEmployee = new BMSEmployee();
        try {
            if (StringUtils.isEmpty(wLoginID))
                return wBMSEmployee;
            List<BMSEmployee> wBMSEmployeeList = this.BMS_QueryEmployeeList(wLoginUser, null, wLoginID, "", 0, 0, 0, 0,
                    -1, "", Pagination.getDefault(), wErrorCode);
            if (wBMSEmployeeList != null && wBMSEmployeeList.size() > 0) {
                wBMSEmployee = wBMSEmployeeList.get(0);
                wBMSEmployee.LoginName = DesUtil.encrypt(wBMSEmployee.LoginName);
            }
        } catch (Exception ex) {

            wErrorCode.set(ExceptionTypes.Exception.getValue());
            logger.error("BMS_QueryEmployeeByLoginID ", ex);
        }
        return wBMSEmployee;
    }

    public BMSEmployee BMS_QueryEmployeeByLoginName(BMSEmployee wLoginUser, String wLoginName,
                                                    OutResult<Integer> wErrorCode) {
        BMSEmployee wBMSEmployee = new BMSEmployee();
        try {
            if (StringUtils.isEmpty(wLoginName))
                return wBMSEmployee;
            List<BMSEmployee> wBMSEmployeeList = this.BMS_QueryEmployeeList(wLoginUser, null, "", wLoginName, 0, 0, 0,
                    0, -1, "", Pagination.getDefault(), wErrorCode);
            if (wBMSEmployeeList != null && wBMSEmployeeList.size() > 0)
                wBMSEmployee = wBMSEmployeeList.get(0);
        } catch (Exception ex) {

            wErrorCode.set(ExceptionTypes.Exception.getValue());
            logger.error("BMS_QueryEmployeeByLoginName ", ex);
        }
        return wBMSEmployee;
    }

    public BMSEmployee BMS_QueryEmployeeByID(BMSEmployee wLoginUser, int wID, OutResult<Integer> wErrorCode) {
        BMSEmployee wBMSEmployee = new BMSEmployee();
        try {
            if (wID <= 0)
                return wBMSEmployee;
            List<BMSEmployee> wBMSEmployeeList = this.BMS_QueryEmployeeList(wLoginUser, StringUtils.parseListArgs(wID),
                    "", "", 0, 0, 0, 0, -1, "", Pagination.getDefault(), wErrorCode);
            if (wBMSEmployeeList != null && wBMSEmployeeList.size() > 0)
                wBMSEmployee = wBMSEmployeeList.get(0);
        } catch (Exception ex) {

            wErrorCode.set(ExceptionTypes.Exception.getValue());
            logger.error("BMS_QueryEmployeeByID ", ex);
        }
        return wBMSEmployee;
    }

    public int BMS_DeleteEmployee(BMSEmployee wLoginUser, BMSEmployee wEmployee, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {

            String wSQLText = "";
            wSQLText = StringUtils.Format("Delete From {0}.mbs_user", super.getDBName())
                    + " where ID=:ID and Grad=0 and Active=0";
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.clear();
            wParams.put("ID", wEmployee.ID);
            wSQLText = this.DMLChange(wSQLText);
            super.update(wSQLText, wParams);

        } catch (Exception ex) {
            logger.error("BMS_ResetPassword ", ex);
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
        }
        return wErrorCode.Result;
    }

    private int BMS_LoginByStoken(String wLoginName, String wToken, OutResult<Integer> wErrorCode) {
        int wCompanyID = -1;

        try {

            if (StringUtils.isEmpty(wLoginName))
                return wCompanyID;

            if (StringUtils.isEmpty(wToken))
                return wCompanyID;

            wToken = DesUtil.decrypt(wToken, SessionConstants.appSecret);

            String[] wTokenArray = wToken.split("\\+-abc072-\\+");
            if (wTokenArray == null || wTokenArray.length != 5) {
                wCompanyID = -10;
                return wCompanyID;
            }
            String wTokenLoginName = StringUtils.Format("{0}{1}", wTokenArray[3], wTokenArray[1]);
            if (!wLoginName.equalsIgnoreCase(wTokenLoginName)) {
                wCompanyID = -10;
                return wCompanyID;
            }
            Calendar wTokenTime = StringUtils.parseCalendar(
                    StringUtils.Format("{0}-{1} {2}", wTokenArray[2], wTokenArray[4], wTokenArray[0]),
                    "yyyy-MM-dd HH:mm:ss");
            Calendar wStartTime = Calendar.getInstance();
            wStartTime.add(Calendar.MINUTE, -3);

            Calendar wEndTime = Calendar.getInstance();
            wEndTime.add(Calendar.MINUTE, 5);
            if (wTokenTime.compareTo(wEndTime) > 0 || wTokenTime.compareTo(wStartTime) < 0) {

                wCompanyID = -10;
                return wCompanyID;
            }
            wCompanyID = 0;

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.Exception.getValue());
            logger.error("BMS_Login", ex);

        }
        return wCompanyID;
    }

}
